import { checkIdNumberValid } from "../../utils/util";
import { realNameAuth } from "../../utils/api";
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
let index = 0;
let tempImageArr: any = [];
let tempImageReadyArr: any = [];
let baseURL = "http://192.168.0.101:3000";
Page({
  data: {
    nameValue: "",
    carID: "",
    nameErrorMessage: "",
    carIDErrorMessage: "",
    imageFileList: []
  },
  onLoad() {

  },
  // 图片上传前验证
  beforeReadImage(event: any) {
    const { file, callback } = event.detail;
    index = 0;
    this.setData({
      imageFileList: []
    })
    if (Array.isArray(file)) {
      file.forEach((element: any) => {
        if (element.type === 'image') {
          callback(true)
        } else {
          Toast.fail('文件格式不符合');
        }
      });
    } else {
      if (file.type === 'image') {
        callback(true)
      } else {
        Toast.fail('文件格式不符合');
      }
    }

  },
  readyImage(event: any) {
    tempImageReadyArr = [];
    tempImageArr = event.detail.file;
    this.setData({
      imageFileList: tempImageArr
    })
    this.afterReadImage();
  },
  // 图片上传
  afterReadImage() {
    const element = tempImageArr[index];
    if (!element) {
      return;
    }
    this.imageUploadFn(element.url);
  },
  imageUploadFn(url: any) {
    wx.uploadFile({
      url: `${baseURL}/api/file/uploadImage`,
      filePath: url,
      name: 'image',
      success: (res: any) => {
        let data = JSON.parse(res.data);
        tempImageReadyArr.push({
          thumb: data.data[0].thumbnail,
          url: data.data[0].path
        });
        index++;
        this.afterReadImage();
      }
    });
  },
  synchronousSetNameData(msg: any) {
    if (!msg.detail) {
      this.setData({
        nameErrorMessage: "姓名不允许为空",
        nameValue: ""
      })
    }

    if (msg.detail) {
      this.setData({
        nameErrorMessage: "",
        nameValue: msg.detail
      })
    }
  },
  synchronousSetCarIdNameData(msg: any) {
    if (!msg.detail) {
      this.setData({
        carIDErrorMessage: "省份证号不允许为空",
        carID: ""
      })
    }
    if (!checkIdNumberValid(msg.detail)) {
      this.setData({
        carIDErrorMessage: "省份证号不符合规则",
        carID: ""
      })
    }
    if (checkIdNumberValid(msg.detail)) {
      this.setData({
        carIDErrorMessage: "",
        carID: msg.detail
      })
    }
  },
  async onNextPage() {
    const res = await realNameAuth({
      realName: this.data.nameValue,
      identityCard: this.data.carID
    })
    if(res.flag){
      wx.switchTab({
        url:"../about/about"
      })
    }
    console.log(res);
  }
})